package com.lagou.tomcat.parser;

import com.lagou.tomcat.container.Servlet;
import com.lagou.tomcat.container.Wrapper;
import com.lagou.tomcat.mapper.MappedContext;
import com.lagou.tomcat.mapper.MappedWrapper;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangjinshan
 * @version 1.0
 * @description
 * @date 2021/7/15 上午8:52
 */
public class WebXmlParser {
    private InputStream inputStream;
    private MappedContext mappedContext;

    public WebXmlParser(InputStream inputStream, MappedContext mappedContext) {
        this.inputStream = inputStream;
        this.mappedContext = mappedContext;
    }

    public void parse() {
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(inputStream);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = document.getRootElement();
        // 获取所有servlet配置标签，并进行遍历
        List<Element> servletElements = root.selectNodes("servlet");
        Map<String, MappedWrapper> wrappers = new HashMap<>();
        for (Element servletElement : servletElements) {
            Element servletNameElement = (Element) servletElement.selectSingleNode("servlet-name");
            String servletName = servletNameElement.getStringValue();
            Element servletClassElement = (Element) servletElement.selectSingleNode("servlet-class");

            String servletClass = servletClassElement.getStringValue();
            Element servletMapping = (Element) root.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
            String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
            Class<?> clz = null;
            try {
                clz = mappedContext.getContext().getClassLoader().loadClass(servletClass);
                Wrapper wrapper = new Wrapper(urlPattern, (Servlet) clz.newInstance());
                wrappers.put(mappedContext.getContext().getContextPath()  + urlPattern, new MappedWrapper(wrapper));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        mappedContext.setWrappers(wrappers);
    }
}
